<template></template>
<script>
	import amap from '@/utils/amap-wx.130.js';
	import {
		getAddressCode
	} from "@/api/address";
	import config from '@/config/config'
	export default {
		data() {
			return {
				config,
				amapPlugin: null,
			};
		},
		mounted() {
			this.init();
			this.amapPlugin = new amap.AMapWX({
				key: config.aMapKey,
				center: [121.498586, 31.239637]
			});
		},
		methods: {
			// 初始化地图并且调用
			initMap() {
				let that = this;
				uni.chooseLocation({
					success: function(res) {
						that.amapPlugin.getRegeo({
							location: [res.longitude, res.latitude].join(','),
							success: (data) => {
								console.log('&&&',data)
								getAddressCode(
									data[0].regeocodeData.addressComponent.adcode,
									data[0].regeocodeData.addressComponent.township
								).then((code) => {
									that.$emit("callback", {
										...data[0],
										...res,
										...code
									});
									that.$emit("close");
								});
							},
							fail: (res) => {
								uni.showToast({
									title: '获取位置详细信息失败，请手动选择',
									icon: 'none',
									duration: 1000
								})
							}
						})
					},
					fail() {
						that.$emit("close");
					},
				});
			},

			// 根据当前客户端判断展示不同类型数据
			init() {
				// #ifdef MP-WEIXIN
				this.wechatMap();
				// #endif
				// #ifndef MP-WEIXIN
				this.initMap();
				// #endif
			},

			// 如果是微信小程序单独走微信小程序授权模式
			wechatMap() {
				let that = this;
				uni.authorize({
					scope: "scope.userLocation",
					success() {
						// 允许授权
						that.initMap();
					},
					fail() {
						//拒绝授权
						uni.showModal({
							content: "检测到您没打开获取地址功能权限，是否去设置打开？",
							confirmText: "确认",
							cancelText: "取消",
							success: (res) => {
								if (res.confirm) {
									// 打开设置好后重新刷新地图
									uni.openSetting({
										success: (res) => {
											that.initMap();
										},
									});
								} else {
									// 取消后关闭
									that.$emit("close");
									return false;
								}
							},
						});
						return false;
					},
				});
			}
		},
	};
</script>
<style lang="scss" scoped>
</style>
